package org.sunriz.server;

import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.sunriz.DAO.Signal;
import org.sunriz.utils.Constant;
import org.sunriz.utils.FolderUtil;
import org.sunriz.utils.GetName;
import org.sunriz.utils.InfoGet;

import java.io.*;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;

import static org.sunriz.utils.RegexManager.*;

public class RefNotExist {
    private static String pageNumber = "";
    private static String blockNum = "";

    private static boolean modified = false;


    /**
     * GetAllBlock 类用于处理区块相关的操作。
     * 该类主要负责遍历指定文件夹下的所有文件，并对每个文件的内容进行逐行读取和处理，
     * 包括提取页面编号（pageNumber）和区块ID（blockID）等信息。
     */
    public static void getRefNotExist(){
        // 获取文件列表
        List<File> fileList = FolderUtil.getFileList();
        HashMap<String,List<Signal>> refNotExist = new HashMap<>();

        for (File file : fileList) {

            String fileName = file.getName();
            // 获取文件名
            System.out.println("Output处理文件: " + fileName);
            List<Signal> signals = new ArrayList<>();
            refNotExist.put(fileName,signals);

            // 获取文件内容
            try (BufferedReader reader = new BufferedReader(
                    new InputStreamReader(new FileInputStream(file), Constant.ENCODING))) {
                String line;
                while ((line = reader.readLine()) != null) {

                    // 获取pageNumber
                    Matcher pagePatter = PAGE_PATTERN.matcher(line);
                    if (pagePatter.find()) {
                        pageNumber = InfoGet.getPageNumber(line);
                    }
                    
                    // 如果是Func，那么判断是否是PgAI//PgDI/
                    Matcher funcPattern = FUNC_PATTERN.matcher(line);
                    if (funcPattern.find()) {


                        // 如果是输入点,提取
                        if (line.contains(Constant.PgAI)||line.contains(Constant.PgDI)) {
                            
                            Matcher matcher = TYPE_PATTERN.matcher(line);
                            matcher.find();
                            String type = matcher.group(0).trim();
                            Matcher matcher2 = BLCOK_PATTERN.matcher(line);
                            matcher2.find();
                            blockNum = matcher2.group(2);

                            String paraLine ;
                            reader.readLine();
                            // 获取引用行
                            paraLine = reader.readLine();
                            String[] pageAndBlock = getPageAndBlock(paraLine);
                            String page = pageAndBlock[0];
                            String block = pageAndBlock[1];

                            String nameLine = reader.readLine();
                            String name = GetName.getLastName(nameLine);

                            if (page.equals("65535")||block.equals("65535")) {
                                // 那么这个点是未引用的输入点或是引用有问题的点
                                signals.add(new Signal(name,type,pageNumber,blockNum));
                                modified = true;
                            }

                        }
                    }

                }
            } catch (IOException e) {
                e.printStackTrace();      
            }
        }
        createExcel(refNotExist,modified);
    }

    /**
     * 获取page和block
     * @param paraLine
     * @return page和block  
     */
    private static String[] getPageAndBlock(String paraLine) {
        // 定位关键字符的位置
        int indexB = paraLine.indexOf('B');
        if (indexB == -1) {
            throw new IllegalArgumentException("字符 'B' 未找到");
        }

        int firstCommaIndex = paraLine.indexOf(',', indexB + 1);
        if (firstCommaIndex == -1) {
            throw new IllegalArgumentException("第一个逗号未找到");
        }

        int secondCommaIndex = paraLine.indexOf(',', firstCommaIndex + 1);
        if (secondCommaIndex == -1) {
            throw new IllegalArgumentException("第二个逗号未找到");
        }

        // 提取page和block值
        String page = paraLine.substring(indexB + 1, firstCommaIndex);
        String block = paraLine.substring(firstCommaIndex + 1, secondCommaIndex);

        return new String[]{page, block};
    }

    /**
     * 创建尚未引用点位的excel文件
     */
    private static void createExcel(HashMap<String,List<Signal>> refNotExist,boolean modified) {
        if (modified) {
            String excelName = Constant.EXCEL_NAME;

            // 获取文件路径
            Path filePath = FolderUtil.getFilePath();
            String filePathString = filePath.toString() + "\\" + excelName ;
            File file = new File(filePathString);
            if (!file.exists()) {
                try {
                    file.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            // 创建excel文件
            try (OutputStream outputStream = new FileOutputStream(file)) {
                Workbook workbook = new XSSFWorkbook();
                Sheet sheet = workbook.createSheet("未引用的输入点");

                Row row = sheet.createRow(0);
                row.createCell(0).setCellValue("控制器编号");
                row.createCell(1).setCellValue("页码");
                row.createCell(2).setCellValue("块号");
                row.createCell(3).setCellValue("点名");
                row.createCell(4).setCellValue("类型");

                int i = 1;
                
                for (String fileName : refNotExist.keySet()) {
                    List<Signal> signals = refNotExist.get(fileName);
                    for (Signal signal : signals) {
                        Row row1 = sheet.createRow(i);
                        row1.createCell(0).setCellValue(fileName);
                        row1.createCell(1).setCellValue(signal.getPageNumber());
                        row1.createCell(2).setCellValue(signal.getBlockID());
                        row1.createCell(3).setCellValue(signal.getName());
                        row1.createCell(4).setCellValue(signal.getType());  
                        i++;
                    }
                }

                workbook.write(outputStream);
                outputStream.close();
                System.out.println("✅ 未引用的输入点已生成,文件路径: " + filePathString);

            } catch (IOException e) {
                e.printStackTrace();
            }   
        }else{
            System.out.println("ⓘ 没有未引用的输入点");
        }
     
    }
}
